﻿using System;
using System.Diagnostics;
using System.Text;
using System.Web;
using System.Xml;
using Microsoft.SharePoint;
using CKS.EBE.API;

namespace CKS.EBE
{
    public class WlwHandler : IHttpHandler
    {
        #region IHttpHandler Members
        /// <summary>
        /// IsReusable implmentation for IHttpHandler
        /// </summary>
        public bool IsReusable
        {
            get { return false; }
        }

        /// <summary>
        /// generate response
        /// </summary>
        /// <param name="context"></param>
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                SPWeb web = SPContext.Current.Web;
                string blogUrl = web.Url;
                context.Response.ContentType = "text/xml";
                using (var wlwTextWriter = new XmlTextWriter(context.Response.OutputStream, Encoding.UTF8))
                {
                    wlwTextWriter.Formatting = Formatting.Indented;
                    wlwTextWriter.WriteStartDocument();

                    // manifest tag
                    wlwTextWriter.WriteStartElement("manifest");
                    wlwTextWriter.WriteAttributeString("xmlns", "http://schemas.microsoft.com/wlw/manifest/weblog");

                    // Options 
                    wlwTextWriter.WriteStartElement("options");
                    wlwTextWriter.WriteElementString("clientType", "Metaweblog");
                    wlwTextWriter.WriteElementString("supportsEmbeds", "Yes");
                    wlwTextWriter.WriteEndElement();

                    // Weblog
                    wlwTextWriter.WriteStartElement("weblog");
                    wlwTextWriter.WriteAttributeString("serviceName", web.Title);
                    wlwTextWriter.WriteAttributeString("imageUrl", web.SiteLogoUrl);
                    string editPostUrl = string.Format("{0}/{1}/EditForm.aspx?ID=", blogUrl, Localization.GetListName(Localization.BlogList.Posts, web.Language)) + "{post-id}";
                    wlwTextWriter.WriteAttributeString("postEditingUrl", editPostUrl);
                    wlwTextWriter.WriteAttributeString("adminUrl", blogUrl + "/_layouts/cks/ebe/settings.aspx");
                    wlwTextWriter.WriteAttributeString("adminLinkText", "Manage blog");
                    wlwTextWriter.WriteEndElement();

                    // End manifest
                    wlwTextWriter.WriteEndElement();

                    wlwTextWriter.WriteEndDocument();
                }
            }
            catch (Exception ex)
            {
                Trace.Write("Error in ProcessRequest: " + ex);
            }
        }
        #endregion
    }
}
